import Foundation

// 修改 ExcludableCodingKeys 协议，使其继承自 Hashable
protocol ExcludableCodingKeys: CodingKey, Hashable {
    static var excludedKeys: [Self] { get }
}

extension Decodable where Self: ExcludableCodingKeys {
    static func decode(from decoder: Decoder, excluding keys: [Self]) throws -> Self {
        let container = try decoder.container(keyedBy: Self.self)
        var result: [Self: Any] = [:]
        
        for key in Self.allCases where !keys.contains(key) {
            if let value = try? container.decode(Int.self, forKey: key) {
                result[key] = value
            } else if let value = try? container.decode(String.self, forKey: key) {
                result[key] = value
            } else if let value = try? container.decode(Bool.self, forKey: key) {
                result[key] = value
            }
            // 添加其他类型的支持
        }
        
        // 返回解析后的对象
        return try Self(from: decoder)
    }
}

extension Encodable where Self: ExcludableCodingKeys {
    func encode(to encoder: Encoder, excluding keys: [Self]) throws {
        var container = encoder.container(keyedBy: Self.self)
        
        for key in Self.allCases where !keys.contains(key) {
            // 这里不能直接使用 self[key]，需要通过 Mirror 来获取属性值
            let mirror = Mirror(reflecting: self)
            for child in mirror.children {
                if let codingKey = child.label.flatMap({ Self(stringValue: $0) }), codingKey == key {
                    if let value = child.value as? Int {
                        try container.encode(value, forKey: key)
                    } else if let value = child.value as? String {
                        try container.encode(value, forKey: key)
                    } else if let value = child.value as? Bool {
                        try container.encode(value, forKey: key)
                    }
                    // 添加其他类型的支持
                }
            }
        }
    }
}
